package com.mao.flinkTest;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;


/**
 * @Description:
 * @Param:
 * @Thought:
 * @Author: Wenjie Mao
 * @create： 2022-11-22 14:06
 */
public class BatchWordCount {
    public static void main(String[] args) throws Exception {
        //1. 获取执行环境
        ExecutionEnvironment ev = ExecutionEnvironment.getExecutionEnvironment();
        //2. read data
        DataSource<String> stringDataSource = ev.readTextFile("java\\maoa\\input\\words.txt");
        //3.
        FlatMapOperator<String, Tuple2<String, Long>> operator =
                stringDataSource.flatMap(
                        (String line, Collector<Tuple2<String, Long>> out) -> {
                            String[] words = line.split(" ");
                            for (String word : words) {
                                out.collect(Tuple2.of(word, 1L));
                            }
                        }).returns(Types.TUPLE(Types.STRING, Types.LONG));

        UnsortedGrouping<Tuple2<String, Long>> tupleGroupByWord = operator.groupBy(0);

        AggregateOperator<Tuple2<String, Long>> sum = tupleGroupByWord.sum(1);

        sum.print();

    }
}
